<template>
  <div class="container">
    <div style="display:flex; padding-top: 35px; padding-left: 25px;">
      <el-button @click="goBack" type="plain" text>
        <el-icon>
          <Back />
        </el-icon>返回
      </el-button>
    </div>
    <div class="order-container">
      <div class="order-header">
        <h2>您的订单</h2>
      </div>

      <div class="order-filter">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="全部订单" name="all" ></el-tab-pane>
          <el-tab-pane label="待付款" name="unpaid"></el-tab-pane>
          <el-tab-pane label="待入住" name="unchecked"></el-tab-pane>
          <el-tab-pane label="已完成" name="completed"></el-tab-pane>
          <el-tab-pane label="已取消" name="canceled"></el-tab-pane>
        </el-tabs>
      </div>

      
      <div class="order-list" v-if="orderList.length > 0">
        <div v-for="order in orderList" :key="order.id" class="order-item">
          <div class="order-header-info">
            <span class="order-date">{{ formatDate(order.createTime) }}</span>
            <span class="order-number">订单号: {{ order.id }}</span>
            <span class="order-hotel">睿雅酒店</span>
          </div>

          <div class="order-content">
            <div class="order-goods">
              <div class="picBox">
                <el-image style="width: 100px; height: 80px; border-radius: 10px;" :src="getRoomInfoById(order.checkedRoom)?.picture" fit="contain"/>
              </div>
              <div class="goods-info">
                <div class="goods-name">
                  {{ getRoomInfoById(order.checkedRoom)?.roomName || '未指定房型' }}
                  <span class="goods-snapshot" @click="goToDetailPage(order.checkedRoom)">[客房详情]</span>
                </div>
                <div class="goods-spec">
                  房型规格: {{ getRoomTypeById(order.checkedRoom)?.roomTypeName || '标准间' }}
                </div>
              </div>

              <div class="goods-price">
                <div class="original-text">房间价格</div>
                <div class="actual-price">¥{{ getRoomInfoById(order.checkedRoom)?.price }}</div>
              </div>

              <div class="goods-operation">
                <el-button type="text" v-if="order.status === 1">申请退款</el-button>
                <el-button type="text" v-if="order.status === 2">联系客服</el-button>
                <el-button type="text" v-if="order.status === 5">投诉</el-button>
              </div>

              <div class="goods-total">
                <div class="original-text">实付金额</div>
                <div class="original-price">¥{{ getRoomInfoById(order.checkedRoom)?.price }}</div>
                <div>¥{{ order.amount }}</div>
              </div>

              <div class="goods-status">
                <div>{{ getOrderStatus(order.status) }}</div>
                <el-button type="text" @click="viewOrderDetail(order.id)">订单详情</el-button>
              </div>

              <div class="goods-actions">
                <el-button type="text" v-if="order.status === 1" @click="payOrder(order.id)">立即付款</el-button>
                <el-button type="text" v-if="order.status === 2">取消订单</el-button>
                <el-button type="text" v-if="[4, 5].includes(order.status)">再次预订</el-button>
                <el-button type="text" v-if="order.status === 5">评价</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="no-order" style="height: 200px;" v-else>
        <el-text class="mx-1">暂时没有订单</el-text>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import api from '@/api/index.js';
import { ElMessage } from 'element-plus';
import { userStore } from '@/stores/userInfoStore.js';
import router from '@/router';
import dayjs from 'dayjs';

const activeTab = ref('all');
const orderList = ref([]);//显示过滤后的订单列表
const allOrders = ref([]);//显示所有订单列表
const userStoreInfo = userStore();

// 订单表单数据
const OrdersFormData = ref({
  id: null, // 唯一标识
  userId: null, // 付款用户id
  userAccountNumber: null, // 付款用户的账号
  checkedRoom: null, // 下单的客房id
  amount: null, // 实付金额
  payMethod: null, // 支付方式（1微信支付，2支付宝支付）
  status: null, // 订单状态（1待支付；2已付款,等待入住；3已取消；4入住中；5已完成；6已退款）
  creteTimeBefore: null, // 预定的入住时间
  creteTimeAfter: null, // 实际入住时间
  updateTimeBefore: null, // 预定的离店时间
  updateTimeAfter: null, // 实际离店时间
});

// 过滤订单数据
const filterOrdersByStatus = () => {
  if (activeTab.value === 'all') {
    orderList.value = allOrders.value;
    return;
  }
  orderList.value = allOrders.value.filter(order => {
    switch (activeTab.value) {
      case 'unpaid':
        return order.status === 1;
      case 'unchecked':
        return order.status === 2;
      case 'canceled':
        return order.status === 3;
        case 'completed':
        return order.status === 5;
      default:
        return true;
    }
  });
};

// 监听 activeTab 的变化
watch(activeTab, () => {
  filterOrdersByStatus();
});

// 房间id数组
const RoomIds = ref([]);

// 获取订单数据
const fetchOrderData = async () => {
  OrdersFormData.value.userId = userStoreInfo.userInfo.id;
  try {
    await api.getOrderInCondition(OrdersFormData.value).then((res) => {
      allOrders.value = res.data.data.list || [];
      console.log("订单信息", allOrders.value);
      RoomIds.value = allOrders.value.map(order => order.checkedRoom).filter(checkedRoom => checkedRoom !== null); // 获取所有房间ID

      // 初始化时直接显示所有订单
      filterOrdersByStatus();
    });
  } catch (error) {
    ElMessage.error('订单信息请求异常');
  }
};


// 获取房间信息
const roomInfoList = ref([]); // 存储房间信息
const fetchRoomTypeByRoomIds = async () => {
  await api.getRoomByIds(RoomIds.value).then((res) => {
    roomInfoList.value = res.data.data;
    // console.log("房间具体信息", roomInfoList.value);
  }).catch((error) => {
    ElMessage.error('房间信息请求异常');
  })
}

// 获取房间类型
const roomTypeList = ref([]); //存房间类型的数组
const fetchRoomType = async () => {
  await api.findRoomType().then((res) => {
    roomTypeList.value = res.data.data;
    // console.log("房型具体类型", roomTypeList.value);
  }).catch((error) => {
    ElMessage.error('房间信息请求异常');
  })
};

 // 根据房间 ID 查找
const getRoomInfoById = (roomId) => {
  return roomInfoList.value.find(room => room.id === roomId);
};

// 根据房间 ID 查找类型
const getRoomTypeById = (roomId) => {
  const roomTypeId = getRoomInfoById(roomId)?.roomType
  return roomTypeList.value.find(roomType => roomType.id === roomTypeId);
};

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD');
};

const getOrderStatus = (status) => {
  switch (status) {
    case 1: return '待支付';
    case 2: return '已付款, 等待入住';
    case 3: return '已取消';
    case 4: return '入住中';
    case 5: return '已完成';
    case 6: return '已退款';
    default: return '未知';
  }
};


const payOrder = (orderId) => {
  // 支付逻辑
  console.log('支付订单:', orderId);
};

onMounted(async () => {
  await fetchOrderData();
  await fetchRoomTypeByRoomIds();
  await fetchRoomType();
});

// #region 导航路由
// 导航到DetailPage
const viewOrderDetail = (orderId) => {
  router.push(`/order/detail/${orderId}`);
};
// 导航到DetailPage
function goToDetailPage(id) {
  router.push({
    path: '/index/DetailPage',
    query: {
      id
    }
  });
}

// 返回上一页
const goBack = () => {
  router.back();
};
// #endregion
</script>

<style scoped>
.container {
  min-width: 1280px;
  max-width: 1920px;
  margin: 0 auto;
  padding: 20px 40px;
}

.order-container {
  max-width: 1200px;
  margin: 20px auto;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.order-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.order-filter {
  padding: 0 20px;
  border-bottom: 1px solid #f0f0f0;
}

.order-list {
  padding: 0 20px;
}

.no-order{
  justify-content: center;
  text-align: center;
  display: flex;
}

.order-item {
  margin: 20px 0;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}

.order-header-info {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
  font-size: 12px;
  color: #666;
}

.order-header-info span {
  margin-right: 20px;
}

.order-number {
  color: #999;
}

.order-hotel {
  margin-left: auto;
  color: #666;
}

.order-content {
  padding: 15px;
}

.order-goods {
  display: flex;
  align-items: center;
}

.picBox {
  margin-right: 15px;
  
}

.goods-info {
  flex: 3;
  padding-right: 15px;
}

.goods-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
}

.goods-snapshot {
  color: #999;
  margin-left: 5px;
  cursor: pointer;
}

.goods-spec {
  font-size: 15px;
  color: #999;
}

.goods-price {
  flex: 1;
  text-align: center;
}

.original-text {
  font-size: 15px;
  color: #999;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.actual-price {
  font-size: 14px;
  color: #f40;
  font-weight: bold;
}

.goods-quantity {
  flex: 0.5;
  text-align: center;
  color: #666;
}

.goods-operation {
  flex: 1;
  text-align: center;
}

.goods-total {
  flex: 1;
  text-align: center;
  font-weight: bold;
}

.postage {
  font-size: 12px;
  color: #999;
  font-weight: normal;
}

.goods-status {
  flex: 1;
  text-align: center;
  color: #666;
}

.goods-actions {
  flex: 1;
  text-align: center;
}

.el-button--text {
  color: #666;
  padding: 0;
  margin: 0 5px;
}

.el-button--text:hover {
  color: #f40;
}

</style>